<template>
  <el-dialog :visible="dialogVisible" width="30%" title="新增权限" @close="closeFn">
    <!-- 以下是放置form表单 -->
    <el-form ref="permission" label-width="80px" :rules="permissionRules" :model="permissionForm">
      <el-form-item label="权限名称" prop="title">
        <el-input v-model="permissionForm.title" />
      </el-form-item>
      <el-form-item label="权限标识" prop="code">
        <el-input v-model="permissionForm.code" />
      </el-form-item>
      <el-form-item label="权限描述" prop="description">
        <el-input v-model="permissionForm.description" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-row type="flex" justify="center">
        <el-button @click="closeFn">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import { addPermission, updatePermission } from '@/api/permission'
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 以下是校验规则
      permissionRules: {
        title: [
          { required: true, message: '请输入权限名称', trigger: 'blur' }
        //   { min: 1, max: 4, message: '角色名称长度在 1 到 4 个字符', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入权限标识！', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入权限描述！！不能为空', trigger: 'blur' }
        ]
      },
      // 以下是角色表单输入框的双向绑定
      permissionForm: {
        title: '',
        code: '',
        description: '',
        pid: '',
        type: ''
      }
    }
  },
  methods: {
    closeFn() {
      this.$emit('update:dialogVisible', false)
      //   清空表单数据
      this.permissionForm = {
        title: '',
        code: '',
        description: ''
      }
      // 重置表单校验
      this.$refs.permission.resetFields()
    },
    // 所有新增和编辑逻辑放这里
    async confirm() {
      // 校验表单
      await this.$refs.permission.validate()
      if (this.permissionForm.id) {
        // 调用接口，更新数据
        await updatePermission(this.permissionForm)
        // this.$message.success('编辑成功')
      } else {
        //   调用接口，实现新增
        await addPermission(this.permissionForm)
        // this.$message.success('新增成功')
      }
      //   关闭弹窗
      this.closeFn()
      //   重新渲染数据，需要告诉父组件，帮忙刷新
      this.$emit('updateEvent')
    }

  }
}
</script>

<style>

</style>
